package com.iheima.reggie_take.common;

/**
 * Created with IntelliJ IDEA.
 * ClassName: GlobalExceptionHandler
 * Package: com.iheima.reggie_take.config
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-01-16
 * Time: 17:59
 */

import com.iheima.reggie_take.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理 本质是一个代理
 * annotations 是注解的意思 只要添加了RestController都会拦截
 * ResponseBody 写一个方法 最好返回的是一个JSON数据
 */

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("未知错误");
    }

    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){


        return R.error(ex.getMessage());
    }


}
